package com.isyscore.os.metadata.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.isyscore.os.core.model.entity.DataFlowDefinition;
import com.isyscore.os.core.model.entity.DataFlowGroup;
import com.isyscore.os.core.model.entity.DataFlowTask;
import com.isyscore.os.core.util.InitiallyUtils;
import com.isyscore.os.metadata.manager.QuartzJobManager;
import com.isyscore.os.metadata.model.entity.*;
import com.isyscore.os.metadata.service.DataFlowDefinitionService;
import com.isyscore.os.metadata.service.DataFlowGroupService;
import com.isyscore.os.metadata.service.DataFlowTaskService;
import com.isyscore.os.metadata.service.DataSourceService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

import static com.isyscore.os.metadata.constant.CommonConstant.DATA_FLOW_JOB_GROUP;
import static com.isyscore.os.metadata.constant.CommonConstant.METRIC_CALCULATE_JOB_GROUP;

/**
 * @author wuwx
 */
@Service
@RequiredArgsConstructor
public class TenantService {
    private final DataSourceService dataSourceService;
    private final DatamodelService datamodelService;
    private final DatamodelColumnService datamodelColumnService;
    private final ErRelationService erRelationService;
    private final MetricService metricService;
    private final MetricDimFilterService metricDimFilterService;
    private final MetricGroupService metricGroupService;
    private final MetricJobBatchService metricJobBatchService;
    private final MetricJobBatchResultService metricJobBatchResultService;
    private final MetricMeasureService metricMeasureService;
    private final SqlStatementService sqlStatementService;
    private final QuartzJobManager quartzJobManager;

    private final DataFlowDefinitionService dataFlowDefinitionService;

    private final DataFlowTaskService dataFlowTaskService;
    private final DataFlowGroupService dataFlowGroupService;

    @Transactional(rollbackFor = Exception.class)
    public void saveTenant(String tenantId){
        DataFlowGroup dataFlowGroup = new DataFlowGroup();
        dataFlowGroup.setName("默认");
        dataFlowGroup.setParentId(null);
        dataFlowGroup.setTenantId(tenantId);
        dataFlowGroup.setCreateTime(LocalDateTime.now());
        dataFlowGroupService.save(dataFlowGroup);
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteTenant(String tenantId) {
        InitiallyUtils.markInitially(() -> {
            dataSourceService.remove(Wrappers.lambdaQuery(DataSource.class).eq(DataSource::getTenantId, tenantId));
            datamodelService.remove(Wrappers.lambdaQuery(Datamodel.class).eq(Datamodel::getTenantId, tenantId));
            datamodelColumnService.remove(Wrappers.lambdaQuery(DatamodelColumn.class).eq(DatamodelColumn::getTenantId, tenantId));
            erRelationService.remove(Wrappers.lambdaQuery(ErRelation.class).eq(ErRelation::getTenantId, tenantId));
            //删除指标的关联任务
            List<Metric> metricList=metricService.list(Wrappers.lambdaQuery(Metric.class).eq(Metric::getTenantId, tenantId));
            for(Metric metric:metricList){
                Long metricId = metric.getId();
                if (quartzJobManager.hasTask(metricId,METRIC_CALCULATE_JOB_GROUP)) {
                    quartzJobManager.deleteJob(metricId,METRIC_CALCULATE_JOB_GROUP);
                }
            }
            metricService.remove(Wrappers.lambdaQuery(Metric.class).eq(Metric::getTenantId, tenantId));
            metricDimFilterService.remove(Wrappers.lambdaQuery(MetricDimFilter.class).eq(MetricDimFilter::getTenantId, tenantId));
            metricGroupService.remove(Wrappers.lambdaQuery(MetricGroup.class).eq(MetricGroup::getTenantId, tenantId));
            //此表已被删除，不再处理
//            metricJobBatchService.remove(Wrappers.lambdaQuery(MetricJobBatch.class).eq(MetricJobBatch::getTenantId, tenantId));
            metricJobBatchResultService.remove(Wrappers.lambdaQuery(MetricJobBatchResult.class).eq(MetricJobBatchResult::getTenantId, tenantId));
            metricMeasureService.remove(Wrappers.lambdaQuery(MetricMeasure.class).eq(MetricMeasure::getTenantId, tenantId));
            sqlStatementService.remove(Wrappers.lambdaQuery(SqlStatement.class).eq(SqlStatement::getTenantId, tenantId));
            //停止所有kettle任务
            List<DataFlowDefinition> flowDefinitions=dataFlowDefinitionService.list(Wrappers.lambdaQuery(DataFlowDefinition.class).eq(DataFlowDefinition::getTenantId, tenantId));
            for(DataFlowDefinition dataFlowDefinition:flowDefinitions){
                Long dataFlowDefinitionId = dataFlowDefinition.getId();
                if (quartzJobManager.hasTask(dataFlowDefinitionId,METRIC_CALCULATE_JOB_GROUP)) {
                    quartzJobManager.deleteJob(dataFlowDefinitionId,DATA_FLOW_JOB_GROUP);
                }
            }
            //清除kettle数据
            dataFlowDefinitionService.remove(Wrappers.lambdaQuery(DataFlowDefinition.class).eq(DataFlowDefinition::getTenantId, tenantId));
            dataFlowTaskService.remove(Wrappers.lambdaQuery(DataFlowTask.class).eq(DataFlowTask::getTenantId, tenantId));
            dataFlowGroupService.remove(Wrappers.lambdaQuery(DataFlowGroup.class).eq(DataFlowGroup::getTenantId, tenantId));
            return null;
        });
    }
}
